package com.usian.ai.controller;


import cn.hutool.core.util.StrUtil;
import com.usian.ai.common.Result;
import com.usian.ai.common.config.MinIOConfig;
import com.usian.ai.common.util.MinIOUtils;
import jakarta.annotation.Resource;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @ClassName FileController
 * @Author
 * @Version 1.0
 * @Description FileController
 **/
@RestController
@RequestMapping("file")
@CrossOrigin
public class MinIoController {

    @Resource
    private MinIOConfig minIOConfig;

    @PostMapping("uploadInterviewerImage")
    public Result uploadInterviewerImage(@RequestParam("file") MultipartFile file) throws Exception {

        // 获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StrUtil.isBlank(filename)) {
            return Result.fail();
        }

        filename = "interviewer/" + dealWithoutFilename(filename);
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                                                filename,
                                                file.getInputStream(),
                                                true);

        return Result.ok(imageUrl);
    }

    @PostMapping("uploadInterviewVideo")
    public Result uploadInterviewVideo(@RequestParam("file") MultipartFile file) throws Exception {

        // 获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StrUtil.isBlank(filename)) {
            return Result.fail();
        }

        filename = "interviewVideo/" + dealWithoutFilename(filename);
        String videoUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),
                true);

        return Result.ok(videoUrl);
    }

    private String dealWithFilename(String filename) {
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String fName = filename.substring(0, filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return fName + "-" + uuid + suffixName;
    }

    private String dealWithoutFilename(String filename) {
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return uuid + suffixName;
    }

}
